﻿/**
 * @brief     Tcp客户端 - 异步方式通讯
 * @details   1、创建Tcp客户端
 * @author    Yin
 * @version   1.0
 * @date
 * @copyright
 * @note
 */

#ifndef ASYNCTCPCLIENT_H
#define ASYNCTCPCLIENT_H

#include "common_global.h"

#include <QObject>
#include <QAbstractSocket>
#include <QHostAddress>
#include <QTcpSocket>
#include <QHostInfo>

namespace Common {

	class COMMONSHARED_EXPORT AsyncTcpClient : public QObject
	{
		Q_OBJECT
	public:
		explicit AsyncTcpClient(QObject *parent = nullptr);
		~AsyncTcpClient();

	public:
		/**
		 * @brief getTcpSocket 获取 TcpSocket
		 * @return
		 */
		QTcpSocket * getTcpSocket();

		/**
		 * @brief connectToServer 杩炴帴鏈嶅姟鍣?
		 * @param localPort  本地端口
		 * @param strTargetIp 目标Ip
		 * @param targetPort 目标端口
		 * @param retryTimes 连接次数
		 * @return
		 */
		bool connectToServer(int localPort, QString strTargetIp, int targetPort, const int retryTimes = 3);

		/**
		 * @brief connectToServer 连接服务器
		 * @param strTargetIp 目标Ip
		 * @param targetPort 目标端口
		 * @param retryTimes 连接次数
		 * @return
		 */
		bool connectToServer(QString strTargetIp, int targetPort, const int retryTimes = 3);

		/**
		 * @brief disconnectFromServer 断开连接
		 * @return
		 */
		bool disconnectFromServer();

		/**
		 * @brief  isConnected 检测TCP是否连接
		 * @return bool
		 */
		bool isConnected();

		/**
		 * @brief  sendTcplMsg 发送TCP消息
		 * @param  message 消息内容
		 * @return bool
		 */
		bool sendTcpMsg(QByteArray message);

		/**
		 * @brief  clear 清理缓冲区数据
		 * @return void
		 */
		void clear();

	Q_SIGNALS:
		/**
		 * @brief signalRecvMag 发送接收的消息
		 * @param recvMsg 接收的消息
		 */
		void signalRecvMag(QByteArray recvMsg);

		/**
		 * @brief signalTcpClientError 发送客户端异常消息
		 * @param strError
		 */
		void signalTcpClientError(QString strError);

	public Q_SLOTS:
		/**
		 * @brief slotSocketReadyRead 读取接收的网络数据
		 */
		void slotSocketReadyRead();

		/**
		 * @brief	slotTcpSocketStateChange 查看网络状态
		 * @param	state
		 */
		void slotTcpSocketStateChange(QAbstractSocket::SocketState state);

	private:
		QTcpSocket * m_tcpSocket;           // 客户端
	};

}//namespace Common

#endif // ASYNCTCPCLIENT_H
